package com.kamistoat.meimeistore.commonsecurity.feign;

import com.kamistoat.meimeistore.commoncore.constant.SecurityConstants;
import com.kamistoat.meimeistore.commoncore.utils.ServletUtils;
import com.kamistoat.meimeistore.commoncore.utils.StringUtils;
import com.kamistoat.meimeistore.commoncore.utils.ip.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign请求拦截器，用于同步请求头防止feign之间丢失用户认证
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取请求Request
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (StringUtils.isNotNull(httpServletRequest)) {
            // 获取请求头的所有kv对
            Map<String, String> headers = ServletUtils.getHeaders();
            // 从所有kv对中获取userId，将其同步到 feign请求头中
            String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
            if(StringUtils.isNotEmpty(userId)){
                requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
            }
            // 从所有kv对中获取userName，将其同步到 feign请求头中
            String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
            if(StringUtils.isNotEmpty(userName)){
                requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
            }
            // 从所有kv对中获取 jwt简易用户令牌，将其同步到feign请求头中
            String authentication = headers.get(SecurityConstants.AUTHORIZATION_HEADER);
            if(StringUtils.isNotEmpty(authentication)){
                requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);
            }

            // 配置客户端Ip
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));

        }
    }
}
